﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Diagnostics;
using System.IO;

namespace Opennav.MapGenerator.Map.Labels
{
    public class LabelSubfile
    {
        private int _offset = -1;

        private SortedList<string, Label> _labelMap = new SortedList<string, Label>();
        private List<Label> _labels = new List<Label>();
        private int _ptr = 0;

        public int Offset
        {
            get
            {
                Debug.Assert(_offset >= 0);
                return _offset;
            }
            set
            {
                this._offset = value;
            }
        }

        public Label Create(string label)
        {
            Label lbl;
            string str = PrepareString(label);
            if (!_labelMap.TryGetValue(str, out lbl))
            {
                UTF8Encoding encoding = new UTF8Encoding();
                byte[] data = encoding.GetBytes(str);
                lbl = new Label(data);
                lbl.Offset = _ptr;
                _labelMap[str] = lbl;
                _labels.Add(lbl);
                _ptr += lbl.SavedLength;
            }
            return lbl;
        }

        public void Write(Stream stream)
        {
            foreach (Label label in _labels)
            {
                label.Write(stream);
            }
        }

        private string PrepareString(string label)
        {
            return label.Trim().Replace("ä", "ae").Replace("ö", "oe").Replace("ü", "ue").Replace("ß", "ss");
        }
    }
}
